package me.dwliu.redis.dao;

import me.dwliu.redis.domain.User;
import me.dwliu.redis.exception.UserException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

/**
 * Created by dw.liu on 2016/1/29 0029.
 */
@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void saveUser(final User user) throws UserException {
        stringRedisTemplate.execute(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                connection.set(stringRedisTemplate.getStringSerializer().serialize("user.uid." + user.getId()),
                        stringRedisTemplate.getStringSerializer().serialize(user.getName()));
                return null;
            }
        });

    }

    @Override
    public User getUser(final Long id) throws UserException {

        return stringRedisTemplate.execute(new RedisCallback<User>() {
            @Override
            public User doInRedis(RedisConnection connection) throws DataAccessException {
                byte[] key = stringRedisTemplate.getStringSerializer().serialize("user.uid." + id);
                if (connection.exists(key)) {
                    byte[] value = connection.get(key);

                    String name = stringRedisTemplate.getStringSerializer().deserialize(value);

                    User user = new User(id, name);
                    return user;
                }
                return null;
            }
        });
    }
}
